package com.yzr.common.reflection.questsion;

import com.yzr.common.reflection.document.Cat;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;

/**
 * @description reflection
 * @author: yx-0173
 * @date: 2021-08-11 16:11
 **/
public class ReflectionQuestion {

    public static void main(String[] args) throws Exception {

        /**
         * 通过读取配置文件中的信息，去执行指定的类的方法
         */

        Properties properties = new Properties();
        properties.load(new FileInputStream("CommonUtils/src/main/resources/db.properties"));

        // 获取配置文件中类所在的路径
        String pathName = properties.get("classPath").toString();
        // 获取配置文件中方法名称
        String methodName = properties.get("methodName").toString();

        // 获取对象的类
        Class<?> aClass = Class.forName(pathName);
        // 获取方法名称
        Method method = aClass.getMethod(methodName);
        // 通过class对象创建加载出来的对象的实例
        Object o = aClass.newInstance();
        // 执行方法
        method.invoke(o);
        Class<Integer> type = Integer.TYPE;
        // 获取字段
        Field hi = aClass.getDeclaredField("catName");
        hi.setAccessible(true);
        System.out.println(hi.get(o));

        // 获取无参构造
        Constructor<?> constructor = aClass.getConstructor();
        System.out.println("无参构造器" + constructor);
        Object o1 = constructor.newInstance();

        // 有参构造
        Constructor<?> stringCon = aClass.getConstructor(String.class);
        System.out.println("有参构造器" + stringCon);


        Cat cat = new Cat();
        ClassLoader classLoader = cat.getClass().getClassLoader();
        URL resource = classLoader.getResource("db.properties");
        Properties properties1 = new Properties();
        System.out.println("==============================");
        if (resource != null) {
            InputStream inputStream = resource.openStream();
            if (inputStream.available() != 0) {
                properties1.load(inputStream);
                properties1.forEach((k, v) -> System.out.println("key= " + k + ",value=" + v));
                inputStream.close();
            }
        }
    }
}

